package logic

import (
	"an_ju_ke/models"
	"an_ju_ke/myrpc/internal/svc"
	"an_ju_ke/myrpc/myrpc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *myrpc.UpdateRequest) (*myrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("user_name = ?", in.UserName).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在")
	}
	key := fmt.Sprintf("sms_captcha_user_phone:%s", user.UserPhone)
	get, _ := models.Rdb.Get(models.Ctx, key).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	if user.UserPassword == in.UserPassword {
		return nil, fmt.Errorf("新的密码和旧密码不得相同")
	}
	user.UserPassword = in.UserPassword
	if models.DB.Where("id = ?", user.ID).Updates(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	models.Rdb.Del(models.Ctx, key)
	return &myrpc.UpdateResponse{}, nil
}
